//------------------------------------------------------------------------------
// The contents of this file are subject to the nopCommerce Public License Version 1.0 ("License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at  http://www.nopCommerce.com/License.aspx. 
// 
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. 
// See the License for the specific language governing rights and limitations under the License.
// 
// The Original Code is nopCommerce.
// The Initial Developer of the Original Code is NopSolutions.
// All Rights Reserved.
// 
// Contributor(s): _______. 
//------------------------------------------------------------------------------

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.Model;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using NopSolutions.NopCommerce.Common.Utils;
using NopSolutions.NopCommerce.BusinessLogic.Services;
using NopSolutions.NopCommerce.BusinessLogic.Infrastructure;


namespace NopSolutions.NopCommerce.Web.Templates.Categories
{
    public partial class ProductsInLines1 : BaseNopFrontendUserControl
    {
        private ICategoryService _categoryService;
        private IProductService _productService;
        private IPictureService _pictureService;
        private ICurrencyService _currencyService;
        private ISettingService _settingService;

        public ProductsInLines1() {
            _categoryService = IoC.Resolve<ICategoryService>();
            _productService = IoC.Resolve<IProductService>();
            _pictureService = IoC.Resolve<IPictureService>();
            _currencyService = IoC.Resolve<ICurrencyService>();
            _settingService = IoC.Resolve<ISettingService>();
        }

        protected override void OnInit(EventArgs e) {
            Load += new EventHandler(ProductsInLines1_Load);
            PreRender += new EventHandler(ProductsInLines1_PreRender);

            base.OnInit(e);
            ctrlPriceRangeFilter.ExcludedQueryStringParams = catalogPager.QueryStringProperty;

            ctrlProductSpecificationFilter.ExcludedQueryStringParams = catalogPager.QueryStringProperty;
            ctrlProductSpecificationFilter.CategoryId = this.CategoryId;

            ctrlProductSpecificationFilter.ReservedQueryStringParams = "CategoryId,";
            ctrlProductSpecificationFilter.ReservedQueryStringParams += "orderby,";
            ctrlProductSpecificationFilter.ReservedQueryStringParams += ctrlPriceRangeFilter.QueryStringProperty;
            ctrlProductSpecificationFilter.ReservedQueryStringParams += ",";
            ctrlProductSpecificationFilter.ReservedQueryStringParams += catalogPager.QueryStringProperty;
        }

        void ProductsInLines1_Load(object sender, EventArgs e) {
            if (!Page.IsPostBack) {
                FillDropDowns();
                BindData();
            }
        }

        void ProductsInLines1_PreRender(object sender, EventArgs e) {
            this.pnlFilters.Visible = ctrlPriceRangeFilter.Visible || ctrlProductSpecificationFilter.Visible;
        }

        protected void FillDropDowns() {
            if (_settingService.GetSettingValueBoolean("Common.AllowProductSorting")) {
                ddlSorting.Items.Clear();

                var ddlSortPositionItem = new ListItem(GetLocaleResourceString("ProductSorting.Position"), ((int)ProductSortingEnum.Position).ToString());
                ddlSorting.Items.Add(ddlSortPositionItem);

                var ddlSortNameItem = new ListItem(GetLocaleResourceString("ProductSorting.Name"), ((int)ProductSortingEnum.Name).ToString());
                ddlSorting.Items.Add(ddlSortNameItem);

                var ddlSortPriceItem = new ListItem(GetLocaleResourceString("ProductSorting.Price"), ((int)ProductSortingEnum.Price).ToString());
                ddlSorting.Items.Add(ddlSortPriceItem);

            }
            else {
                pnlSorting.Visible = false;
            }
        }

        protected void BindData() {
            var category = _categoryService.GetCategoryById(this.CategoryId);

            //title
            litTitle.Text = category.LocalizedName;

            //breadcrumb
            rptrCategoryBreadcrumb.DataSource = _categoryService.GetBreadCrumb(this.CategoryId);
            rptrCategoryBreadcrumb.DataBind();

            lDescription.Text = category.LocalizedDescription;

            //subcategories
            var subCategories = _categoryService.GetAllCategoriesByParentCategoryId(category.CategoryId);
            if (subCategories.Count > 0) {
                lvSubCategories.Visible = true;
                lvSubCategories.DataSource = subCategories;
                lvSubCategories.DataBind();
            }
            else {
                lvSubCategories.Visible = false;
            }

            //featured products
            var featuredProducts = category.FeaturedProducts;
            if (featuredProducts.Count > 0) {
                pnlFeaturedProducts.Visible = true;
                rptFeaturedProducts.DataSource = featuredProducts;
                rptFeaturedProducts.DataBind();
            }
            else {
                pnlFeaturedProducts.Visible = false;
            }

            //price ranges
            this.ctrlPriceRangeFilter.PriceRanges = category.PriceRanges;

            //page size
            int totalRecords = 0;
            int pageSize = 10;
            if (category.PageSize > 0) {
                pageSize = category.PageSize;
            }

            //price ranges
            decimal? minPrice = null;
            decimal? maxPrice = null;
            decimal? minPriceConverted = null;
            decimal? maxPriceConverted = null;
            if (ctrlPriceRangeFilter.SelectedPriceRange != null) {
                minPrice = ctrlPriceRangeFilter.SelectedPriceRange.From;
                if (minPrice.HasValue) {
                    minPriceConverted = _currencyService.ConvertCurrency(minPrice.Value, NopContext.Current.WorkingCurrency, _currencyService.PrimaryStoreCurrency);
                }

                maxPrice = ctrlPriceRangeFilter.SelectedPriceRange.To;
                if (maxPrice.HasValue) {
                    maxPriceConverted = _currencyService.ConvertCurrency(maxPrice.Value, NopContext.Current.WorkingCurrency, _currencyService.PrimaryStoreCurrency);
                }
            }

            //specification filter
            var psoFilterOption = ctrlProductSpecificationFilter.GetAlreadyFilteredSpecOptionIds();

            //sorting
            ProductSortingEnum orderBy = ProductSortingEnum.Position;
            if (_settingService.GetSettingValueBoolean("Common.AllowProductSorting")) {
                CommonHelper.SelectListItem(this.ddlSorting, CommonHelper.QueryStringInt("orderby"));
                orderBy = (ProductSortingEnum)Enum.ToObject(typeof(ProductSortingEnum), int.Parse(ddlSorting.SelectedItem.Value));
            }

            var productCollection = _productService.GetAllProducts(this.CategoryId,
                0, 0, false, minPriceConverted, maxPriceConverted,
                string.Empty, false, pageSize, this.CurrentPageIndex,
                psoFilterOption, orderBy, out totalRecords);

            if (productCollection.Count > 0) {
                this.catalogPager.PageSize = pageSize;
                this.catalogPager.TotalRecords = totalRecords;
                this.catalogPager.PageIndex = this.CurrentPageIndex;

                this.pnlProductList.Visible = true;
                this.pnlSorting.Visible = true;

                this.rptCatalog.DataSource = productCollection;
                this.rptCatalog.DataBind();
            }
            else {
                this.pnlProductList.Visible = false;
                this.pnlSorting.Visible = false;
            }
        }

        protected void ddlSorting_SelectedIndexChanged(object sender, EventArgs e) {
            string url = CommonHelper.GetThisPageUrl(true);
            url = CommonHelper.ModifyQueryString(url, "orderby=" + ddlSorting.SelectedItem.Value, null);
            Response.Redirect(url);
        }

        protected void OnSubCategoriesRepeaterItemDataBound(object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
                var category = e.Item.DataItem as Category;
                string categoryURL = SEOHelper.GetCategoryUrl(category);

                var hlImageLink = e.Item.FindControl("hlImageLink") as HyperLink;
                if (hlImageLink != null) {
                    hlImageLink.ImageUrl = _pictureService.GetPictureUrl(category.PictureId, _settingService.GetSettingValueInteger("Media.Category.ThumbnailImageSize", 125), true);
                    hlImageLink.NavigateUrl = categoryURL;
                    hlImageLink.ToolTip = String.Format(GetLocaleResourceString("Media.Category.ImageLinkTitleFormat"), category.LocalizedName);
                    hlImageLink.Text = String.Format(GetLocaleResourceString("Media.Category.ImageAlternateTextFormat"), category.LocalizedName);
                }

                var hlCategory = e.Item.FindControl("hlCategory") as HyperLink;
                if (hlCategory != null) {
                    hlCategory.NavigateUrl = categoryURL;
                    hlCategory.ToolTip = String.Format(GetLocaleResourceString("Media.Category.ImageLinkTitleFormat"), category.LocalizedName);
                    hlCategory.Text = Server.HtmlEncode(category.LocalizedName);
                }
            }
        }

        public ISettingService SettingService {
            get { return _settingService; }
        }

        public int CurrentPageIndex {
            get {
                int _pageIndex = CommonHelper.QueryStringInt(catalogPager.QueryStringProperty);
                _pageIndex--;
                if (_pageIndex < 0)
                    _pageIndex = 0;
                return _pageIndex;
            }
        }

        public int CategoryId {
            get {
                return CommonHelper.RouteStringInt("categoryId");
            }
        }
    }
}